package com.zzyl.nursing.controller.member.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.controller.member.service.MemberHealthyDataservice;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.PropertyStatusInfo;
import com.zzyl.nursing.dto.AlertDataDto;
import com.zzyl.nursing.dto.QueryHealthyDataDto;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.MemberHealthyDataMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class MemberHealthyDataServiceImpl implements MemberHealthyDataservice {
    //引入redis模板
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberHealthyDataMapper memberHealthyDataMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private AlertDataMapper alertDataMapper;
    /**
     * 查询健康数据
     */
    public List<HealthyDataVo> queryServiceProperties(String iotId){
        //从redis中获取数据存入集合中
        List<HealthyDataVo> healthyDataVos = new ArrayList<>();

        // 从Redis中根据iotId查询健康数据
        Object o = redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
        if (o != null) {
            // 将获取到的数据反序列化
            String jsonStr = o.toString();
            
            // 解析JSON数组
            List<Object> dataList = JSONUtil.toList(jsonStr, Object.class);
            
            // 遍历数据列表，转换为HealthyDataVo对象
            for (Object item : dataList) {
                // 将Object转换为JSONObject
                cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(item);
                
                // 创建HealthyDataVo实例
                HealthyDataVo vo = new HealthyDataVo();
                
                // 设置functionId
                vo.setFunctionId(jsonObject.getStr("functionId"));
                
                // 设置eventTime（对应alarmTime）
                Object alarmTimeObj = jsonObject.get("alarmTime");
                if (alarmTimeObj != null) {
                    String alarmTimeStr = alarmTimeObj.toString();
                    if (!alarmTimeStr.isEmpty()) {
                        try {
                            long timestamp = Long.parseLong(alarmTimeStr);
                            // 判断是秒级时间戳还是毫秒级时间戳
                            if (alarmTimeStr.length() == 10) {
                                // 秒级时间戳
                                LocalDateTime alarmTime = LocalDateTime.ofInstant(
                                    java.time.Instant.ofEpochSecond(timestamp),
                                    ZoneId.of("Asia/Shanghai")
                                );
                                vo.setEventTime(alarmTime.toString());
                            } else if (alarmTimeStr.length() == 13) {
                                // 毫秒级时间戳
                                LocalDateTime alarmTime = LocalDateTime.ofInstant(
                                    java.time.Instant.ofEpochMilli(timestamp),
                                    ZoneId.of("Asia/Shanghai")
                                );
                                vo.setEventTime(alarmTime.toString());
                            } else {
                                // 其他情况，直接使用原始值
                                vo.setEventTime(alarmTimeStr);
                            }
                        } catch (NumberFormatException ex) {
                            // 如果解析时间戳失败，记录日志并使用原始值
                            log.warn("时间戳解析失败，alarmTime: {}", alarmTimeStr, ex);
                            vo.setEventTime(alarmTimeStr); // 保留原始值
                        }
                    } else {
                        vo.setEventTime(null);
                    }
                } else {
                    vo.setEventTime(null);
                }
                
                // 设置Value（对应dataValue）
                Object dataValue = jsonObject.get("dataValue");
               if (dataValue == null){
                   throw new RuntimeException("dataValue为空");
               }else
               // 将dataValue转换为long
                 vo.setValue(Long.parseLong(dataValue.toString()));
                // 添加到结果列表
                healthyDataVos.add(vo);
            }
        } else {
            // 数据为空时返回空集合，不抛出异常
            log.info("健康数据为空，iotId: {}", iotId);
        }

        return healthyDataVos;
    }

    /**
     * 按天统计查询指标数据
     */
    @Override
    public List<DeviceDataByDay> queryDeviceDataListByDay(String iotId, String functionId, Long startTime, Long endTime){
        //将开始时间和结束时间进行解析
        LocalDateTime startDateTime = LocalDateTimeUtil.of(startTime);
        LocalDateTime endDateTime = LocalDateTimeUtil.of(endTime);
        //根据iotId\functionId\startTime\endTime查询数据
        return deviceDataMapper.queryDeviceDataListByDay(iotId, functionId, startDateTime, endDateTime);
    }
    /**
     * 查询家人列表
     */
    @Override
    public List<BindingElderInfoVo> selectBindingElderInfoVoList(){
        //获取当前登录用户的id
        Long loadUserId = UserThreadLocal.getUserId();
        return memberHealthyDataMapper.selectBindingElderInfoVoList(loadUserId);
    }
    /**
     * 获取已绑定老人列表
     */
    public List<ElderMessageVo> selectElderMessageVoList(){
        //获取当前登录用户的id
        Long userId = UserThreadLocal.getUserId();
        //获取已绑定老人列表
        return memberHealthyDataMapper.selectElderMessageVoList(userId);
    }
    /**
     * 查询健康数据
     */
    public HealthyMessageVo queryDeviceServiceProperties(String deviceName, String productKey) {
        //根据deviceName查询设备
        DeviceInfo deviceInfo = deviceService.queryDeviceInfoByDeviceName(deviceName);
        if (deviceInfo == null) {
            throw new BaseException("设备不存在");
        }
        //获取设备ID
        String iotId = deviceInfo.getIotId();
        //从redis中获取最新数据
        Object o = redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
        if (o == null) {
            throw new BaseException("设备数据不存在");
        }
        String jsonStr = o.toString();
        //创建集合
        List<PropertyStatusInfo> propertyStatusInfos = new ArrayList<>();
        List<Object> dataList = JSONUtil.toList(jsonStr, Object.class);
        // 遍历循环赋值
        for (Object item : dataList) {
            cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(item);
            PropertyStatusInfo propertyStatusInfo = new PropertyStatusInfo();
            // 设置 dataType
            propertyStatusInfo.setDataType("double");
            // 设置 identifier（functionId）
            propertyStatusInfo.setIdentifier(jsonObject.getStr("functionId"));
            //获取到identifier
            String identifier = propertyStatusInfo.getIdentifier();
            // 设置 name（deviceName）
            if (identifier.equals("xueyang")){
                propertyStatusInfo.setName("血氧");
            } else if (identifier.equals("HeartRate")){
            propertyStatusInfo.setName("心率");}
            else if (identifier.equals("BodyTemp")){
            propertyStatusInfo.setName("体温");}
            else if (identifier.equals("BatteryPercentage")){
            propertyStatusInfo.setName("用电量");}
            else  // 设置 name（deviceName）
            {
                propertyStatusInfo.setName(jsonObject.getStr("deviceName"));
            }

            // 设置 time（createTime）
            String createTimeStr = jsonObject.getStr("createTime");
            if (createTimeStr != null && !createTimeStr.isEmpty()) {
                propertyStatusInfo.setTime(createTimeStr);
            }
            // 设置 value（dataValue）
            Object dataValue = jsonObject.get("dataValue");
            if (dataValue != null) {
                propertyStatusInfo.setValue(dataValue);
            }
            // 设置 unit
            propertyStatusInfo.setUnit( "double");
            propertyStatusInfos.add(propertyStatusInfo);
        }
        HealthyMessageVo healthyMessageVo = new HealthyMessageVo();
        healthyMessageVo.setPropertyStatusInfo(propertyStatusInfos);
        return healthyMessageVo;
    }
    /**
     * 按周统计查询指标数据
     */
    public List<DeviceDataByDay> queryDeviceDataListByWeek(String iotId, String functionId, Long startTime, Long endTime){
        //将开始时间和结束时间进行解析
        LocalDateTime startDateTime = LocalDateTimeUtil.of(startTime);
        LocalDateTime endDateTime = LocalDateTimeUtil.of(endTime);
        return deviceDataMapper.queryDeviceDataListByWeek(iotId, functionId, startDateTime, endDateTime);
    }
    /**
     * 查询告警数据
     */
    public List<AlertData> pageQueryAlertData(AlertDataDto alertDataDto){
        //获取分页数据
        PageHelper.startPage(alertDataDto.getPageNum(), alertDataDto.getPageSize());

        // 执行查询（此处应调用具体的mapper方法）
        AlertData alertData = new AlertData();
        //将alertDataDto中的属性复制到alertData对象中
        BeanUtils.copyProperties(alertDataDto, alertData);
        return alertDataMapper.selectAlertDataList(alertData);


    }
}